<!-- 云端渲染面板通用 -->
<template>
    <div class="cloudRender">
        <!-- loading -->
        <div v-if="loading" :class="loading ? 'cloudLoading' : ''">
            <div class="spinner">
                <div class="bounce1"></div>
                <div class="bounce2"></div>
                <div class="bounce3"></div>
            </div>
            <div class="title">lnitialzing</div>
        </div>
        <!-- 场景 -->
        <div id="cloud">
        </div>
        <!-- 时间 -->
        <div class="time" v-if="showTime">
            <div class="dashboard-time" v-show="isShowTime">
                <span class="time">{{time}}</span>
                <span class="weekStr">{{day}} {{weekStr}}</span>
            </div>
        </div>
    </div>
</template>

<script>
    import {
        mapState
    } from 'vuex'
    import cloudRenderer from "superapi-51world"
    import { SetLiftPoiOption, SetGreenMarkPoiOption } from '@/util/poiOption'
    const marker = document.location.origin + '/static/Lift/Lift_marker_img.png'
    // const label = document.location.origin + '/static/Lift/Lift_label_bgi.png'
    export default {
        name: 'cloudvr',
        props: [''],
        data() {
            return {
                // cloudRender: null,
                config: this.setting,
                loading: true,
                // 显示隐藏时间
                isShowTime: false,
                // 时间设置参数
                timer: '',
                time: '',
                weekStr: '',
                day: '',
                flag: 0
            };
        },

        components: {

        },

        computed: {
            showTime() {
                return this.$store.state.app.showTime
            },
            liftPoiData() {
                return this.$store.state.app.liftPoiData
            },
            greenMarkPoiData() {
                return this.$store.state.app.greenMarkPoiData
            }
        },
        mounted() {

            // 设置时间
            this.setInitTime()
            // 开启云服务
            this.startCloudRenderServer();
            // 初始化
            // this.setState_Initial();
            // 结束云渲染
            this.$once('hook:beforeDestory', this.endCloundRenderServer);
        },

        methods: {
            //开启服务
            startCloudRenderServer() {
                var cloudRender = new cloudRenderer("cloud", 0);
                window.cloudRender = cloudRender;
                // this.cloudRender = cloudRender;
                fetch(`${this.config.url}/autoLogin`, {
                        method: "POST",
                        body: `username=${this.config.username}&pwd=${this.config.password}`,
                        headers: {
                            "Content-type": "application/x-www-form-urlencoded"
                        },
                    })
                    .then((res) => res.json())
                    .then((json) => {
                        //console.log(json, '第一次请求')
                        if (json.success) {
                            fetch(`${this.config.url}/Renderers/Any/${this.config.guid}`, {
                                    method: "POST",
                                    headers: {
                                        "Content-type": "application/x-www-form-urlencoded",
                                        Authorization: `Bearer ${json.token}`,
                                    },
                                    body: `width=${window.innerWidth}&height=${window.innerHeight}`,
                                })
                                .then((res) => res.json())
                                .then((json) => {
                                    console.log(json, '第二次请求')
                                    if (json.success) {
                                        cloudRender.SuperAPI("StartRenderCloud", json.url);
                                        console.log(json.url, 111);

                                        cloudRender.SuperAPI(
                                            "RegisterCloudResponse",
                                            this.cloudRenderListener
                                        );
                                    } else {
                                        alert(json.error)
                                    }
                                });
                        } else {
                            alert(json.error)
                        }
                    }).catch(error => {
                        alert(error);
                    });
            },
            //关闭云渲染服务
            endCloundRenderServer() {
                cloudRender.SuperAPI("StopRenderCloud")
            },
            useLayerAPI(name, status) {
                //STATUS 0 为打开，1 为关闭图层
                cloudRender.SuperAPI("specialChannel", {
                    actionname: `${name}`,
                    status: status,
                });
            },
            // 初始化
            setState_Initial() {
                // 调用非标API隐藏全部图层
                this.useLayerAPI("OverviewMoutain", 1);
                this.useLayerAPI("OverviewWater", 1);
                this.useLayerAPI("OverviewForest", 1);
                this.useLayerAPI("OverviewField", 1);
                this.useLayerAPI("OverviewLake", 1);
                this.useLayerAPI("OverviewGrass", 1);
                this.useLayerAPI("OverviewArchitecture", 1);
                this.useLayerAPI("OverviewFacility", 1);
                // this.InitCamera();
            },
            // 切换远镜头poi-maker
            toggleFarPoiMaker(markerSize) {
                if (this.liftPoiData.length < 1) return
                this.liftPoiData.forEach((it) => {
                    let data = {
                        id: it.guid,
                        marker: {
                            size: markerSize,
                            images: [{
                                define_state: "state_1",
                                normal_url: SetLiftPoiOption(it.state).markerUrl,
                                activate_url: ''
                            }]
                        }
                    }

                    window.cloudRender.SuperAPI("UpdateCustomPOIMarker", data)
                });
            },
            _toggleFarPoiMaker(markerSize) {
                if (this.greenMarkPoiData.length < 1) return
                this.greenMarkPoiData.forEach((it) => {
                    let data = {
                        id: it.guid,
                        marker: {
                            size: markerSize,
                            images: [{
                                define_state: "state_1",
                                normal_url: SetGreenMarkPoiOption(it.awardachieved).markerUrl,
                                activate_url: ''
                            }]
                        }
                    }

                    window.cloudRender.SuperAPI("UpdateCustomPOIMarker", data)
                });
            },
            // 切换近镜头poi-maker
            toggleNearPoiMaker(markerSize) {
                if (this.liftPoiData.length < 1) return
                this.liftPoiData.forEach((it) => {
                    let data = {
                        id: it.guid,
                        marker: {
                            size: markerSize,
                            images: [{
                                define_state: "state_1",
                                normal_url: marker,
                                activate_url: marker
                            }]
                        }
                    }

                    window.cloudRender.SuperAPI("UpdateCustomPOIMarker", data)
                });
            },
            _toggleNearPoiMaker(markerSize) {
                if (this.greenMarkPoiData.length < 1) return
                this.greenMarkPoiData.forEach((it) => {
                    let data = {
                        id: it.guid,
                        marker: {
                            size: markerSize,
                            images: [{
                                define_state: "state_1",
                                normal_url: marker,
                                activate_url: marker
                            }]
                        }
                    }

                    window.cloudRender.SuperAPI("UpdateCustomPOIMarker", data)
                });
            },
            // 更新自定义POi点Label
            updatePoiLabel() {
                if (this.liftPoiData.length < 1) return
                this.liftPoiData.forEach((it) => {
                    let option = SetLiftPoiOption(it.state)
                    let jsondata = {
                        "id": it.guid,
                        "label": {
                            "bg_image_url": option.labelUrl,
                            "bg_size": "176,33",
                            "bg_offset": "1,80",
                            "content": [{
                                "text": [option.title, 'ffffffff', "14"],
                                "text_offset": "2,4"
                            }]
                        }
                    }
                    window.cloudRender.SuperAPI("UpdateCustomPOILabel", jsondata)
                });
            },
            _updatePoiLabel() {
                if (this.greenMarkPoiData.length < 1) return
                this.greenMarkPoiData.forEach((it) => {
                    let option = SetGreenMarkPoiOption(it.awardachieved)
                    let jsondata = {
                        "id": it.guid,
                        "label": {
                            "bg_image_url": 'http://superapi.51hitech.com/doc-static/images/static/LabelBg.png', //option.labelUrl
                            "bg_size": "280,33",
                            "bg_offset": "4,80",
                            "content": [{
                                "text": [it.awardachieved, 'ffffffff', "14"],
                                "text_offset": "2,4"
                            }]
                        }
                    }
                    window.cloudRender.SuperAPI("UpdateCustomPOILabel", jsondata)
                });
            },
            // 更新自定义POI点Window
            updatePoiWindow() {
                if (this.liftPoiData.length < 1) return
                this.liftPoiData.forEach((it) => {
                    let jsondata = {
                        "id": it.guid,
                        "window": {
                            "url": "",
                            "size": "550,400",
                            "offset": "40,200"
                        }
                    }
                    window.cloudRender.SuperAPI("UpdateCustomPOIWindow", jsondata)
                });
            },
            _updatePoiWindow() {
                if (this.greenMarkPoiData.length < 1) return
                this.greenMarkPoiData.forEach((it) => {
                    let jsondata = {
                        "id": it.guid,
                        "window": {
                            "url": "",
                            "size": "550,400",
                            "offset": "40,200"
                        }
                    }
                    window.cloudRender.SuperAPI("UpdateCustomPOIWindow", jsondata)
                });
            },
            // 更新自定义POI点的样式 
            updatePoiStyle() {
                if (this.liftPoiData.length < 1) return
                this.liftPoiData.forEach((it) => {
                    let jsondata = {
                        "id": it.guid,
                        "always_show_label": false,
                        "show_label_range": "0,6000",
                        "sort_order": false,
                        "state": "state_1"
                    }
                    window.cloudRender.SuperAPI("UpdateCustomPOIStyle", jsondata)
                });
            },
            _updatePoiStyle() {
                if (this.greenMarkPoiData.length < 1) return
                this.greenMarkPoiData.forEach((it) => {
                    let jsondata = {
                        "id": it.guid,
                        "always_show_label": false,
                        "show_label_range": "0,6000",
                        "sort_order": false,
                        "state": "state_1"
                    }
                    window.cloudRender.SuperAPI("UpdateCustomPOIStyle", jsondata)
                });
            },
            // 云渲染监听
            cloudRenderListener(e) {
                let jsonObject = JSON.parse(e);
                switch (jsonObject.func_name) {
                    case "APIAlready":
                        // 3D世界加载完成 do Something
                        this.loading = false;
                        this.isShowTime = true
                        console.log('3D世界加载完成');
                        cloudRender.SuperAPI("SetMultiRendering", {
                            screenpercentage: 1,
                        });
                        this.$store.commit('app/SET_USERNAME', "3d-world-ready");
                        break;

                    case "OnPOIClick":
                        console.error("OnPOIClick ID: " + jsonObject.args.id);
                        // let FocusCoveringjsondata = {
                        //     "id": jsonObject.args.id, //覆盖物id
                        //     "covering_type": "poi", //覆盖物类型, 详见下表
                        //     "distance": 200 //距离(单位:米), 默认20米
                        // }
                        // window.cloudRender.SuperAPI("FocusCovering", FocusCoveringjsondata, (status, progress) => {
                        //     console.log(status, progress, '镜头移动');
                        // })
                        break;
                    case "OnSuperAPIInputActionEnd":
                        if (jsonObject.args.action === 'mouse_wheel') {
                            let jsondata = {
                                "coord_type": 0,
                                "cad_mapkey": ""
                            }
                            window.cloudRender.SuperAPI("GetCameraInfo", jsondata, (e) => {
                                const distance = JSON.parse(e).arm_distance
                                console.log('距离是' + distance);
                                if (this.$route.path === '/LIFT') {
                                    if (distance > 5000 && this.flag < 1) {
                                        this.updatePoiStyle()
                                        this.toggleFarPoiMaker('30,30')
                                        console.log('加载了');
                                        this.flag++
                                        // this.updatePoiWindow()
                                    } else if (distance <= 5000 && this.flag > -1) {
                                        this.toggleNearPoiMaker('7,90')
                                        console.log('加载了');
                                        this.updatePoiLabel()
                                        this.flag--
                                    }
                                    console.log(this.flag, '5555555555555');
                                }
                                if (this.$route.path === '/GREENMARK') {
                                    if (distance > 5000 && this.flag < 1) {
                                        this._updatePoiStyle()
                                        this._toggleFarPoiMaker('30,30')
                                        console.log('加载了');
                                        this.flag++
                                        // this.updatePoiWindow()
                                    } else if (distance <= 5000 && this.flag > -1) {
                                        this._toggleNearPoiMaker('7,90')
                                        console.log('加载了');
                                        this._updatePoiLabel()
                                        this.flag--
                                    }
                                    console.log(this.flag, '5555555555555');
                                }
                            })
                        }
                        break;
                    case "OnCustomWebJsEvent":
                        // Bus.$emit('window-event', {
                        //   eventName: jsonObject.args.name,
                        //   data: jsonObject.args.args
                        // });
                        break;
                }
                return e;
            },
            // 设置时间
            setInitTime() {
                this.timer = setInterval(() => {
                    this.time = this.moment(new Date()).format('LTS');
                })
                let str = "";
                let week = new Date().getDay();
                if (week == 0) {
                    str = "Sunday";
                } else if (week == 1) {
                    str = "Monday";
                } else if (week == 2) {
                    str = "Tuesday";
                } else if (week == 3) {
                    str = "Wednesday";
                } else if (week == 4) {
                    str = "Thursday";
                } else if (week == 5) {
                    str = "Friday";
                } else if (week == 6) {
                    str = "Saturday";
                }
                this.day = this.moment().format('L').slice(5);
                this.weekStr = str;
            }
        },

        watch: {},
        beforeDestory() {
            clearInterval(this.timer)
        },

    }
</script>
<style lang='less' scoped>
    #cloud {
        z-index: 0;
    }
</style>